<template>
  <div>
    <div class="bg-white">
      <!-- <a-alert showIcon class="mt-10">
        <span slot="message"
          >门店交付点是门店另设的与门店地址不同的交付地址，该地址提供对范围5km以内的区域提供“门店取还车”服务，预定顾客可以前往交付点取还车。</span
        >
      </a-alert> -->
<!-- 
      <div class="py-20 relative b-line">
        <div class="flex justify-between">
          <div class="flex items-center">
            <select-store
              v-model="storeId"
              class="ml-8"
              style="width: 200px"
              placeholder="请选择一个门店"
              @change="onStoreChange"
            ></select-store>

            <a-button
              type="primary"
              icon="plus"
              class="ml-20"
              @click="addTableHandle"
              v-if="$permissionJudge('StoreServicePointCreate')"
              >新建交付点
            </a-button>
            <a-button type="primary" ghost class="ml-20" @click="toStoreSettingGuideHandle">门店设置教程>></a-button>
          </div>
        </div>
      </div> -->

      <div class="p-10">
        <a-table :columns="columns" class="" :data-source="pageList" :pagination="false">
          <!--门店-->
          <!-- <template #store="val, data">
            <div>
              {{ storeDetailData && storeDetailData.name }}
            </div>
          </template> -->
          <template #address="val, data">
            <div>
              {{ data.address }}<img
                style="width: 18px"
                @click="setMapPoint2(data)"
                src="@/assets/icons/pin.png"
                alt=""
                class="cursor-pointer mx-9"
              />
            </div>
          </template>

          <!--操作-->
          <template #set="val, data">
            <div>
              <a class="mr-10" @click="editHandle(data)" v-if="$permissionJudge('StoreServicePointUpdate')">编辑</a>
              <a class="mr-10 text-red-501" @click="delHandle(data)" v-if="$permissionJudge('StoreServicePointDelete')"
                >删除</a
              >
            </div>
          </template>
        </a-table>
      </div>
    </div>

    <!--地图-->
    <div class="p-10">
      <div id="container3" style="height: 700px"></div>
    </div>

    <!--修改增值服务报价弹框s-->
    <a-modal
      :title="info ? '修改门店交付点' : '新建门店交付点'"
      :visible="isShowAddPointPop"
      @cancel="isShowAddPointPop = false"
      :width="640"
      @ok="handleSubmit"
    >
      <div class="mx-20">
        <a-form :form="addPointForm">
          <a-row :gutter="12">
            <a-col :span="24">
              <a-form-item
                label="名称"
                labelAlign="left"
                :labelCol="{ span: 4, offset: 0 }"
                :wrapperCol="{ span: 20, offset: 0 }"
              >
                <a-input
                  :maxLength="60"
                  placeholder="请输入名称"
                  v-decorator="['name', { rules: [{ required: true, message: '请输入名称', whitespace: true }] }]"
                />
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item
                label="联系方式"
                labelAlign="left"
                :labelCol="{ span: 4, offset: 0 }"
                :wrapperCol="{ span: 20, offset: 0 }"
              >
                <a-input
                  :maxLength="11"
                  placeholder="请输入联系方式"
                  v-decorator="[
                    'telephone',
                    {
                      rules: [
                        {
                          required: true,
                          whitespace: true,
                          message: '请输入联系方式',
                          validator: $utils.phoneValidator,
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item
                label="交付地址"
                labelAlign="left"
                :labelCol="{ span: 4, offset: 0 }"
                :wrapperCol="{ span: 20, offset: 0 }"
              >
                <div class="flex items-center" @click="setMapPoint()">
                  <a-input
                    :maxLength="200"
                    placeholder="请选择交付地址"
                    :disabled="true"
                    v-decorator="[
                      'address',
                      { rules: [{ required: true, message: '请选择交付地址', whitespace: true }] },
                    ]"
                  />

                  <a-tooltip placement="top" title="点击选择地址">
                    <img class="cursor-pointer w-20 h-20 ml-10" :src="pin" />
                  </a-tooltip>
                </div>

                <a-input type="hidden" v-decorator="['id']" />
                <a-input type="hidden" v-decorator="['storeId']" />
                <a-input type="hidden" v-decorator="['longitude']" />
                <a-input type="hidden" v-decorator="['latitude']" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-modal>
    <!--修改增值服务报价弹框e-->

    <!--选择地图的弹框s-->
    <!-- <AddressComponent ref="AddressComponent" :city="city" @uploadPoint="uploadPoint"></AddressComponent> -->
    <!--选择地图的弹框e-->
    <AddressComp ref="map" />
  </div>
</template>

<script>
import { servicePointList } from '@/api/store/index'

import { getStoreDetail } from '@/api/store/index'
import AddressComp from '@/views/order/order-manage/AddressComp' //点击地图

// import AddressComponent from '../../component/AddressComponent'
import { createRole, editRoleBaseInfo } from '@/api/role'

export default {
  name: 'deliveryPointItem',
  components: {
    AddressComp
    // AddressComponent,
  },
    props: {
    storeId2: {
      // 门店id
      type: String,
      default: null,
    },
    servicePointpageList:{
      type:Array
    }
  },
  data() {
    return {
      storeId: undefined, // 门店id
      storeList: [], // 门店列表
      loading: true, // 页面是否在加载中
      pageList: [], // 列表总数据

      isShowAddPointPop: false, // 是否新建门店交付点弹框
      addPointForm: this.$form.createForm(this), // form对象
      pin: require('@/assets/icons/pin.png'),

      columns: [
        // 表格头部
        { title: '交付点名称', dataIndex: 'name' },
        { title: '交付点地址', dataIndex: 'address' ,scopedSlots: { customRender: 'address' }},
        // { title: '门店', scopedSlots: { customRender: 'store' } },
        { title: '联系方式', dataIndex: 'telephone' },
      ],
      storeDetailData: null, // 门店详情数据
      info: null,
      city: undefined, //门店所在城市
    }
  },

  computed: {
    storeList() {
      // 门店列表
      return this.$store.getters.storeList
    },
  },

  async created() {
    // if (this.storeList.length > 0) {
    //   this.storeId = this.storeList[0].id
    //   await this.getData() // 获取交付点列表数据
    //   await this._getStoreDetail() // 获取门店详情数据
    //   this.iniMap() // 初始化地图
    // } else {
    //   this.loading = false
    // }
  },

  methods: {
    /*地图相关s*/
    iniMap() {
      this.map = new AMap.Map('container3', {
        center: [this.storeDetailData.longitude, this.storeDetailData.latitude],
        zoom: 12,
      })

      let centerList = this.pageList.map((x) => {
        return {
          position: [x.longitude, x.latitude],
          name: x.name,
        }
      })

      centerList.map((x) => {
        this.creatCircle(x.position)
        this.addCenterMark(x.position, x.name)
      })
    },

    addCenterMark(center, text) {
      // 添加中心覆盖物文案
      let textMark = new AMap.Text({
        text,
        anchor: 'center', // 设置文本标记锚点
        style: {
          padding: '5px 5px',
          'background-color': '#1791fc',
          'border-width': '2px',
          'text-align': 'center',
          'font-size': '14px',
          color: '#ffffff',
          'border-color': 'rgba(0,0,0,.1)',
          'border-style': 'solid',
          'max-width': '300px',
          opacity: 1,
        },
        position: center,
      })
      textMark.setMap(this.map)
    },

    creatCircle(center) {
      // 绘制圆
      let circle = new AMap.Circle({
        center,
        radius: 5000, //半径
        borderWeight: 3,
        strokeColor: 'rgba(24,144,255,.01)',
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        strokeStyle: 'solid',
        strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: '#1791fc',
        zIndex: 50,
      })
      this.map.add(circle)

      let iconMark = new AMap.Marker({
        position: center,
        anchor: 'center',
        size: new AMap.Size(30, 30),
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        offset: new AMap.Pixel(6, -30),
        zIndex: 50,
      })
      this.map.add(iconMark)
    },

    /*地图相关e*/
    getData(storeId, isLoading = true) {
      // 获取列表
      return new Promise((resolve, reject) => {
        this.loading = true
        servicePointList({
          storeId: storeId, // 门店id
        })
          .then((res) => {
            this.pageList = res
            console.log(this.pageList);
            console.log(123123);
            this.iniMap()
            resolve()
          })
          .finally(() => {
            this.loading = false
          })
      })
    },

    _getStoreDetail(id) {
      // 门店详情
      return new Promise((resolve, reject) => {
        getStoreDetail({
          storeId: id, // 门店id
        })
          .then((res) => {
            this.city = res.cityName
            this.storeDetailData = res
            resolve()
          })
          .finally(() => {
            this.loading = false
          })
      })
    },

    async onStoreChange(e) {
      // 门店改变的时候触发
      await this.getData() // 获取交付点列表数据
      await this._getStoreDetail() // 获取门店详情数据
      this.iniMap() // 初始化地图
    },
    async editHandle(e) {
      // 编辑
      let res = await this._getServicePointDetail(e)
      this.info = res
      this.isShowAddPointPop = true
      this.$nextTick(() => {
        this.addPointForm.setFieldsValue({
          id: res.id,
          storeId: res.storeId,
          name: res.name,
          telephone: res.telephone,
          address: res.address,
          longitude: res.longitude,
          latitude: res.latitude,
        })
      })
    },

    _getServicePointDetail(e) {
      // 获取详情
      return new Promise((resolve, reject) => {
        getServicePointDetail({ id: e.id }).then((res) => {
          resolve(res)
        })
      })
    },

    delHandle(e) {
      // 删除服务范围
      if (this.isAllEditOrAddTableItem) return this.$message.error('请先保存/取消当前编辑项')
      this.$confirm({
        title: '提示',
        content: `确定要删除【${e.name}】吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this._deleteServicePoint(e)
        },
      })
    },

    _deleteServicePoint(e) {
      // 删除交付点
      deleteServicePoint({ id: e.id }).then(() => {
        this.$message.success('删除成功')
        this.getData()
      })
    },

    setMapPoint() {
      // 打开地图弹框
      let { address, longitude, latitude } = this.addPointForm.getFieldsValue()
      this.$refs.AddressComponent.getAddressValue({ address, longitude, latitude, type: 2 })
    },

    uploadPoint(data) {
      console.log(data, '地图回调')
      this.addPointForm.setFieldsValue({
        address: data.address,
        longitude: data.longitude,
        latitude: data.latitude,
      })
    },

    addTableHandle() {
      // 打开弹框
      this.isShowAddPointPop = true
      this.info = null
      this.$nextTick(() => {
        this.addPointForm.setFieldsValue({
          id: 0,
          storeId: this.storeId,
          name: '',
          telephone: '',
          address: '',
          longitude: 0,
          latitude: 0,
        })
      })
    },

    handleSubmit(e) {
      // 表单提交
      console.log(e)
      e.preventDefault()
      this.addPointForm.validateFields((err, values) => {
        console.log(values)
        if (!err) {
          const confirmFn = values.id > 0 ? editServicePoint : createServicePoint
          confirmFn(this.$utils.trimValue(values))
            .then(async () => {
              this.$message.success(`${values.id > 0 ? '修改' : '新增'}成功！`)
              this.isShowAddPointPop = false
              await this.getData() // 获取交付点列表数据
              this.iniMap() // 初始化地图
            })
            .finally(() => {})
        }
      })
    },
    toStoreSettingGuideHandle() {
      // 去门店指引
      this.$router.push({ name: 'StoreSettingGuide', query: { storeId: this.storeId } })
    },
        setMapPoint2(data, label = 'pickup') {
      console.log(data)
      this.$refs.map.setMapPoint({
        longitude: data['longitude'],
        latitude: data['latitude'],
        content: data[ 'address'],
      })
    },
  },
}
</script>

<style scoped>
</style>